package Demo66;

/**
 * 最长回文子串
 * https://leetcode.cn/problems/longest-palindromic-substring/
 *
 * 中⼼扩散
 */
class Solution {
    public String longestPalindrome(String s) {
        int begin = 0, len = 0, n = s.length();
        // 确定中心点
        for(int i = 0; i < n;i++) {
            // 遍历奇数的情况
            int left = i,right = i;
            while(left >= 0 && right < n && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }
            if(right - left - 1 > len) {
                begin = left + 1;
                len = right - left - 1;
            }
            // 偶数情况
            left = i;right = i + 1;
            while(left >= 0 && right < n && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }
            if(right - left - 1 > len) {
                begin = left + 1;
                len = right - left - 1;
            }
        }
        return s.substring(begin,begin + len);
    }
}